package v1

import (
	"arlog/core/k8s"
	log "arlog/core/logs"
	"arlog/utils/res"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func Demo(c *gin.Context) {

	/*	pods, err := k8s.ClientSet.CoreV1().
			Pods("default").
			List(context.TODO(), v1.ListOptions{})

		if err != nil {
			log.Panic(err.Error())

		}
		var podList []gin.H

		for _, item := range pods.Items {
			podList = append(podList, gin.H{
				"namespace": item.Namespace,
				"name":      item.Name,
				"ip":        item.Status.PodIP,
				"status":    item.Status.Phase,
			})
		}

		// 统一返回 JSON 数组
		res.Ask(c, 200, gin.H{
			"code":   200,
			"msg":    "OK",
			"result": podList,
		})*/

	gvr := schema.GroupVersionResource{
		Group:    "kubevirt.io",
		Version:  "v1",
		Resource: "virtualmachineinstances",
	}

	// 4、发送请求，且得到返回结果(动态客户端获取到的是非结构化结构体，需要用非结构化变量去存储)
	vmis, err := k8s.DynamicClient.Resource(gvr).Namespace("").List(context.TODO(), v1.ListOptions{})
	if err != nil {
		log.Panic(err.Error())
	}

	var podList []gin.H
	for _, item := range vmis.Items {

		fmt.Println("Name:", item.GetName())
		fmt.Println("Namespace:", item.GetNamespace())
		jsonData, _ := item.MarshalJSON()
		// 一次性获取多个字段
		results := gjson.GetMany(string(jsonData), "status.phase", "status.interfaces.0.ipAddress")

		phase := results[0].String()
		ipAddress := results[1].String()

		podList = append(podList, gin.H{
			"name":      item.GetName(),
			"namespace": item.GetNamespace(),
			"ip":        ipAddress,
			"status":    phase,
		})

	}
	res.Ask(c, 200, podList)

}
